Container的職責在於創建、配置與組裝bean,昨天我們學到了
如何如何使用@Autowire註解將bean組裝
今日將討論如何使用@Value的用法、完全註解開發、泛型依賴注入
透過Java Class來取代xml的配置文件,在未來的很多Spring Project會看到以此種方式配置
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.swj"})
public class SpringConfig {
}
@Test
public void testDay16(){
ApplicationContext ioc = new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("容器啟動完成....");
for (String name :ioc.getBeanDefinitionNames()){
System.out.println(name);
}
}
Result
先前在Day13 SpEL有提到在註解中也可以使用SpEL,通常我們會透過@Value作為使用,此外引入的Properties也可以透過@Value將Properties的資訊引入
創建測試類,須注意Properties取值是使用${},SpEL是使用#{}
package com.swj.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
@Component
public class AnnotationValue {
@Value("${sys.env}")
private String env;
//Spring 提供可以取得系統參數的物件
@Value("#{systemEnvironment}")
private Properties properties;
//可以透過[]取得特定系統參數值
@Value("#{ systemProperties['user.country'] }")
private String country;
@Override
public String toString() {
return "AnnotationValue{" +
"env='" + env + '\'' +
", country='" + country + '\'' +
", properties=" + properties +
'}';
}
}
建立properties設定檔名為sys.properties
# sys.properties
sys.env=SIT
@ComponentScan的另一個設定方式,與設定Properties的路徑
@Configuration
@ComponentScan(basePackageClasses = {com.swj.component.AnnotationValue.class})
@PropertySource("classpath:sys.properties")
public class SpringConfig {
}
測試
@Test
public void testDay16(){
ApplicationContext ioc = new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("容器啟動完成....");
AnnotationValue value = ioc.getBean("annotationValue",AnnotationValue.class);
System.out.println(value);
}
Result
EmpService、TradeService因確定泛型類型使得父類BaseService中的Dao能夠正確注入對應的Dao
public class Employee {
}
public class Trade {
}
public abstract class BaseDao <T>{
public abstract void save();
}
@Repository
public class TradeDao extends BaseDao<Trade> {
@Override
public void save() {
System.out.println("儲存交易資訊");
}
}
@Repository
public class EmpDao extends BaseDao<Employee> {
@Override
public void save() {
System.out.println("儲存員工資訊");
}
}
public class BaseService <T>{
@Autowired
private BaseDao<T> baseDao;
public void save(){
System.out.println("autowired dao"+baseDao);
baseDao.save();
}
}
@Service
public class EmpService extends BaseService<Employee> {
}
@Service
public class TradeService extends BaseService<Trade> {
}
@Test
public void testDay16(){
ApplicationContext ioc = new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("容器啟動完成....");
EmpService empService = ioc.getBean("empService",EmpService.class);
TradeService tradeService = ioc.getBean("tradeService",TradeService.class);
empService.save();
tradeService.save();
}
Result